package com.yax.yapi.plug;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import javafx.scene.control.Tab;
import javafx.scene.layout.GridPane;

import java.util.*;

/**
 * @Author: yax
 * @Date: 2021/2/4 15:20
 */
public interface PlugIntf {
  default int width(){
    return 720;
  }
  default int height(){
    return 500;
  }
  void buildTabs(String username,String cookie,List<Tab> tabs);

  void buildTransferComponent(GridPane grid, int columnIndex, Map<String, Object> componentMap);

  void transferIdHandle(String username,String cookie,List<String> idList,Map<String, Object> componentMap);

  default void apiTransformation(JSONObject data, Map<String, Object> componentMap,boolean isUpdate, String newPath, Properties prop,String project_id, String catid, String id){
    String method = data.getString("method");
    if ("POST".equals(method)) {
      data.put("method", "GET");
      String req_body_other = data.getString("req_body_other");
      JSONObject reqBodyJson = JSONObject.parseObject(req_body_other, Feature.OrderedField);
      JSONObject properties = reqBodyJson.getJSONObject("properties");
      JSONArray jsonArray = reqBodyJson.getJSONArray("required");
      List<String> required = JSONArray.parseArray(jsonArray.toString(), String.class);
      List<Map<String, Object>> req_query = new ArrayList<>();
      for (String name : properties.keySet()) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        JSONObject property = properties.getJSONObject(name);
        String description = property.getString("description");
        map.put("desc", description);
        map.put("required", required.contains(name) ? "1" : "0");
        map.put("example", "");
        req_query.add(map);
      }
      data.put("req_query", req_query);
      data.remove("req_body_other");
      data.put("req_headers", new ArrayList<>());
      data.remove("req_body_type");
    }
    String path = data.getString("path");
    data.put("path", path);
    if (newPath != null && !"".equals(newPath)) {
      data.put("path", newPath);
    }
    String updatePath = prop.getProperty(path);
    if (isUpdate && updatePath != null && !"".equals(updatePath)) {
      data.put("path", updatePath);
    }
    data.put("catid", catid);
    data.put("project_id", project_id);
  }
}
